import React, { useState } from "react";
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";
import "./App.css";

function App(props) {
  //定义状态用于保存任务列表
  const [taskList, setTaskList] = useState([]);
  //添加任务
  function addTask(e) {
    //是按下了回车
    if (e.keyCode === 13) {
      //获取写入的任务标题
      const title = e.target.value.trim();
      //判断任务标题是否为空
      if (title.length === 0) {
        alert("请输入任务标题!");
        return;
      }
      //判断任务标题是否重复
      const index = taskList.findIndex((v) => v.title === title);
      if (index > -1) {
        alert("请不要输入重复任务标题!");
        return;
      }
      setTaskList([
        {
          id: Math.random().toString(36).slice(2),
          title,
          isChecked: false,
        },
        ...taskList,
      ]);
      //清空value
      e.target.value = null;
    }
  }

  //改变选中状态
  function changeIsChecked(id) {
    setTaskList(
      taskList.map((item) => {
        if (item.id === id) {
          item.isChecked = !item.isChecked;
        }
        return item;
      })
    );
  }

  //根据id 删除数据
  function delTaskById(id) {
    setTaskList(taskList.filter((item) => item.id !== id));
  }

  //已完成数据
  function finCount() {
    return taskList.reduce((pre, curr) => {
      return (pre += curr.isChecked ? 1 : 0);
    }, 0);
  }

  //删除已完成
  function deleteAllFin() {
    setTaskList(taskList.filter((item) => !item.isChecked));
  }

  //全选摁钮
  function changeIsCheckedAll(isChecked) {
    setTaskList(
      taskList.map((item) => {
        console.log(item.isChecked);
        item.isChecked = isChecked;
        return item;
      })
    );
  }
  return (
    <div className="todo-container">
      <div className="todo-wrap">
        <TodoHeader addTask={addTask} />
        <TodoMain
          changeIsChecked={changeIsChecked}
          taskList={taskList}
          delTaskById={delTaskById}
        />
        <TodoFooter
          taskList={taskList}
          finCount={finCount}
          deleteAllFin={deleteAllFin}
          changeIsCheckedAll={changeIsCheckedAll}
        />
      </div>
    </div>
  );
}

export default App;
